<template>
  <div>
    <!-- <div class="tag-container box box-ac">
      发票类型：
      <div class="tag-list box box-f1">
        <div @click="changeTag(index,'billType')" v-for="(item, index) in billType.list" :class="{act:item.id==billType.checked}" class="animated tag-item box box-ac box-pc">{{item.name}}</div>
      </div>
    </div> -->
    <div class="tips-line">
      发票信息
    </div>
    <div class="box box-ver">
      <div class="line-input last-bor-0 box box-ac">
        <div class="title">发票代码</div>
        <div class="text box box-ac box-f1">{{invoicecode}}</div>
      </div>
      <div class="line-input last-bor-0 box box-ac">
        <div class="title">发票号码</div>
        <div class="text box box-ac box-f1">{{invoicenumber}}</div>
      </div>
      <div class="line-input last-bor-0 box box-ac">
        <div class="title">开票日期</div>
        <div class="text box box-ac box-f1">{{invoicedate}}</div>
      </div>
      <div class="line-input last-bor-0 box box-ac">
        <div class="title">开票金额</div>
        <div class="text box box-ac box-f1">{{invoiceamount}}</div>
      </div>
    </div>
    <code-tpl ref="codeTpl2" @codeChange="changeBillType" :invoicecode="invoicecode" :invoicenumber="invoicenumber"></code-tpl>
    <div class="tips-line">
      <span>*</span>请选择报销类别
    </div>
    <div class="business-container box bor-none">
      <div @click="changeTag(index,'businessType')" v-for="(item, index) in businessType.list" :value="item" :key="index"  :class="{act:index===businessType.checkedIndex}" class="item box box-f1 box-ac box-pc box-ver">
        <div :class="'icon-business'+(index+1)" class="icon animated"></div>
        <div class="text">{{item.name}}</div>
      </div>
    </div>
    <div class="h-bot"></div>
    <div class="btn-bot box w-p100">
      <div @click="checkInvoice(1)" class="box box-f1 box-pc box-ac w-p100">保存并继续添加</div>
      <div @click="checkInvoice(2)" class="box box-f1 box-pc box-ac w-p100 opposite">保存至发票夹</div>
    </div>
  </div>
</template>

<script>
import config from '@/js/config'
import { readAsDataURL } from '../js/common'
import { openToast, popup } from '@/js/tools'
import codeTpl from '@/components/codeTpl'
import { mapState } from 'vuex'
export default {
  components: {
    codeTpl
  },
  data () {
    return {
      code: {
        imagecontent: '',
        imagetype: ''
      },
      invoicecode: '042001600111',
      invoicenumber: '46458090',
      invoiceamount: '', // 不含税金额
      totalamount: '', // 校验码后六位
      checkCode: '',
      invoicedate: '请选择开票日期',
      pdfuuid: '',
      isjym: null, // 1-普票 输入校验码后六位 0-不含税金额
      invoiceresult: null,
      businessType: {
        checkedIndex: '',
        list: [{
          name: '住宿费',
          id: 1
        }, {
          name: '餐饮费',
          id: 2
        }, {
          name: '通讯费',
          id: 3
        }, {
          name: '其他',
          id: 4
        }]
      }
    }
  },
  computed: {
    ...mapState(['userNum'])
  },
  mounted () {
    // this.$store.state.scanBillCode = '01,04,1200153320,07041662,183.49,20151221,83623873463907646339,5080,'
    let _this = this
    let AscanBillCode = this.$store.state.scanBillCode.split(',')
    this.invoicecode = AscanBillCode[2]
    this.invoicenumber = AscanBillCode[3]
    this.invoiceamount = AscanBillCode[4]
    this.invoicedate = AscanBillCode[5].substring(0, 4) + '-' + AscanBillCode[5].substring(4, 6) + '-' + AscanBillCode[5].substring(6, 8)
    this.checkCode = AscanBillCode[6]
    _this.$nextTick(() => {
      _this.$refs.codeTpl2.getCode()
    })
  },
  methods: {
    Scan () {
      let _this = this
      // _this.$router.push('/addScanBill')
      wx.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
        success: function (res) {
          let result = res.resultStr // 当needResult 为 1 时，扫码返回的结果
          console.log(result, result.substring(0, 3), result.split(',').length)
          if (result.substring(0, 3) !== '01,' || result.split(',')[3].length !== 8) {
            _this.$router.go(-1)
            openToast({
              msg: '请扫描发票二维码',
              duration: 2000
            })
          } else {
            _this.$store.commit('scanBillCode', result)
            location.reload()
          }
        }
      })
    },
    changeBillType (isjym) {
      // alert(isjym)
      this.isjym = isjym
      this.totalamount = (+isjym === 1) ? this.checkCode.substring(this.checkCode.length - 6, this.checkCode.length) : this.invoiceamount
    },
    changeTag (index, data) {
      this[data].checkedIndex = index
    },
    /**
     *
    */
    checkInvoice (type) {
      // _this.Scan()
      let _this = this
      let checkkey = this.$store.state.checkkey
      let invoicecode = _this.invoicecode
      let invoicenumber = _this.invoicenumber
      let invoicedate = _this.invoicedate.replace(/-/g, '')
      let totalamount = _this.totalamount
      // 验证码
      let $codeTpl = _this.$refs.codeTpl2
      let imagecode = $codeTpl.imagecode
      let yzmsj = $codeTpl.yzmsj
      let ymmj = $codeTpl.ymmj
      if (!_this.businessType.checkedIndex && _this.businessType.checkedIndex !== 0) {
        openToast({
          msg: '请选择报销类别',
          duration: 2000
        })
        return
      }
      let detailedtype = _this.businessType.list[_this.businessType.checkedIndex].id
      if (invoicecode.length !== 10 && invoicecode.length !== 12) {
        openToast({
          msg: '发票代码为10或12位数字',
          duration: 2000
        })
        return
      }
      if (invoicenumber.length !== 8) {
        openToast({
          msg: '发票号码为8位数字',
          duration: 2000
        })
        return
      }
      if (_this.invoicedate.split('-').length !== 3) {
        openToast({
          msg: '请选择开票日期',
          duration: 2000
        })
        return
      }
      if (!_this.isjym) {
        openToast({
          msg: '请先获取验证码',
          duration: 2000
        })
        return
      }
      if (+_this.isjym === 1) {
        if (!_this.totalamount) {
          openToast({
            msg: '请填写校验码后六位',
            duration: 2000
          })
          return
        }
      } else {
        if (!_this.totalamount) {
          openToast({
            msg: '请填写不含税金额',
            duration: 2000
          })
          return
        }
      }
      if (!_this.$refs.codeTpl2.imagecode) {
        openToast({
          msg: '请填写验证码',
          duration: 2000
        })
        return
      }
      _this.$http({
        $vue: _this,
        type: 'XML',
        method: 'post',
        url: config.GXUrl + '/CheckInvoice/services/AutoImageCenter.ws?wsdl',
        data: {
          servername: 'CheckInvoice',
          data: {
            checkkey: checkkey,
            checktype: '4',
            invoicecode,
            invoicenumber,
            totalamount,
            imagecode,
            invoicedate,
            yzmsj,
            ymmj
          }
        }
      }).then(item => {
        if (+item.result['#text'] === 0) {
          _this.invoiceresult = JSON.parse(item.invoiceresult['#text'])
          _this.saveInvoice(type)
        }
      })
    },
    saveInvoice (type) {
      let _this = this
      let datasource = 5
      // 发票类型
      let detailedtype = _this.businessType.list[_this.businessType.checkedIndex].id
      // 不含税金额
      _this.invoiceamount = _this.invoiceresult.jamount
      // 总金额
      let totalamount = _this.invoiceresult.totalamount
      _this.$http({
        $vue: _this,
        type: 'XML',
        method: 'post',
        url: config.GXUrl + '/CheckInvoice/services/AutoImageCenter.ws?wsdl',
        data: {
          servername: 'saveInvoice',
          data: {
            useraccount: _this.userNum,
            invoicecode: _this.invoicecode,
            invoicenum: _this.invoicenumber,
            invoicedate: _this.invoicedate,
            invoiceamount: _this.invoiceamount,
            totalamount: totalamount,
            detailedtype,
            datasource,
            pdfuuid: _this.pdfuuid,
            checkresult: 1,
            gfnsrsbh: _this.invoiceresult.inaccount,
            gfname: _this.invoiceresult.inname,
            xfnsrsbh: _this.invoiceresult.outaccount,
            xfname: _this.invoiceresult.outname,
            tnvoicetype: _this.invoiceresult.fplx,
            machinecode: _this.invoiceresult.fpjqm,
            fpjym: _this.invoiceresult.fpjym,
            filepath: '',
            invoicekey: ''
          }
        }
      }).then(item => {
        if (+item.result['#text'] === 0) {
          if (type === 2) {
            _this.$router.replace('/myInvoice')
          } else {
            _this.Scan()
            // location.reload()
            // _this.$router.go(0)
          }
        }
        // popup({
        //   tpl: 'alert',
        //   title: '提示',
        //   content: '保存成功共',
        //   buttons: ['<div class="tc-main">是</div>', '否'],
        //   buttonCallBack: function (index) {
        //     if (index === 0) {
        //       _this.$router.replace('/myInvoice')
        //     }
        //   }
        // })
      })
    }
  },
  watch: {
    // '$router': {

    // }
  }
}
</script>

<style lang="scss" scoped>
@import '../css/color';
@import '../css/mixins';
.tag-container{
  padding-top:.2rem;
  padding-bottom:.2rem;
  background-color:#FFF;
  padding-left:.3rem;
  border-bottom:1px solid $borderColor;
  .tag-list{
    padding-top:.2rem;
    padding-left:.1rem;
    .tag-item{
      margin:0 .22rem;
    }
  }
}
</style>
